// 引入SDK核心类
// 实例化API核心类
// var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')
// let qqMap = new QQMapWX({
//   key: 'BP2BZ-GTNK3-Q6S3Q-YRF3H-7N32T-DNBCL' // 必填
// })
var amapFile = require('./../../utils/amap-wx.js');//如：..­/..­/libs/amap-wx.js
const app = getApp();
var voice = "";
import { request } from '../../utils/index.js';
// import { request } from './../../utils/util.js';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify.js';
var dateTimePicker = require('../../utils/util.js')
Page({

  /**
   * 组件的初始数据
   */
  data: {
    detailOrderlist: '',
    detailList: '',
    checked: true,
    plusFlag: true, // 添加未修改之前
    crossFlag: false, // ×
    takeOverFlag: false,
    showFlag: false, // 修改号码
    valuePhone: '',
    valueAddress: '',
    addressFlag: false, // 收货地址标记
    timeFlag: false, // 修改时间标记
    longitude: 113.324520,
    latitude: 23.099994,
    markers: [{
      id: 0,
      iconPath: "../../resources/location.png",
      latitude: 23.099994,
      longitude: 113.324520,
      width: 50,
      height: 50
    }],
     dateTimeArray: null,
     dateTime: null,
     dateTimeArrayEnd: null,
     dateEndTime: null,
     startYear: 2000,
     endYear: 2050,
     delySTime: '',
     delyETime: '',
     src: '',
     tips: {}
  },
  //获取当前位置
  controlshandler(event) {
    console.log(event)
    // 如果是定位的小图标
    // if (event.controlId === 1) {
    //   // 获取本认所在地的经纬度 ---- 调用微信的定位功能
    //   // api-位置       https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.stopLocationUpdate.html
    //   wx.getLocation({
    //     success: (res) => {
    //       console.log(res)
    //       const { longitude, latitude } = res
    //       this.setData({
    //         longitude, latitude,

    //       })
    //     }
    //   })
    // }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDetail(options)
    // 获取完整的年月日 时分秒，以及默认显示的数组
     var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear)
     var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
     
     this.setData({
       dateTimeArray: obj.dateTimeArray,
       dateTime: obj.dateTime,
       dateTimeArrayEnd: obj1.dateTimeArray,
       dateEndTime: obj1.dateTime
     });
  },
  onShow: function () {
    var _this = this;
    _this.controlshandler()
  },
  // /**
  //  * 请求详情页
  //  */
  getDetail(options) {
    const ordNo = options.proid
    try {
      const token = wx.getStorageSync('token')
      if (token !== '') {
        request({
          url: '/detail',
          method: 'GET',
          data: {
            token: token,
            ordNo: ordNo
          },
          header: {
            'content-type': 'application/json',
            'token': `${token}`
          }
        }).then(res => {
          if(res.data.code == 200) {
            if (res.data.result == '') {
              this.setData({
                prolisting: '',
                invoiceHeadering: ''
              })
            } else {
              let result = res.data.result.items;
              result.forEach(item => {
                item.disgetPrice = (item.disPrice/100).toFixed(2);
              })
              this.setData({
                detailList: res.data.result.items,
                detailOrderlist: res.data.result.order
              })
            }
          } else {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          }
        })
      }
    } catch (e) {
      //console.error(e)
    }
  },
  // //滑动渐入渐出
  // slideupshow: function (that, param, px, opacity) {
  //   var animation = wx.createAnimation({
  //     duration: 800,
  //     timingFunction: 'ease',
  //   });
  //   animation.translateY(px).opacity(opacity).step()
  //   //将param转换为key
  //   var json = '{"' + param + '":""}'
  //   json = JSON.parse(json);
  //   json[param] = animation.export()
  //   //设置动画
  //   that.setData(json)
  // },
  // 修改按钮点击
  modify(e) {
    this.setData({
      plusFlag: false,
      crossFlag: true,
      takeOverFlag: true
    })
  },
  modifyed() {
    this.setData({
      plusFlag: true,
      crossFlag: false,
      takeOverFlag: false
    })
  },
  
  // 修改号码
  updatePhone(e) {
    this.setData({
      showFlag: true
    })
  },
  // 取消修改手机号码
  cancelUpdatePhone() {
    this.setData({
      showFlag: false
    })
  },
  // 修改手机号码
  formSubmit: function (e) {
    const ordNo = e.currentTarget.dataset.id
    const cneeTel = e.detail.value.valuePhone
    try {
      const token = wx.getStorageSync('token')
      if (token !== '') {
        request({
          url: '/updateOrder',
          method: 'POST',
          data: {
            token: token,
            ordNo: ordNo,
            cneeTel: cneeTel
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'token': `${token}`
          }
        }).then(res => {
          // if(res) {}13876899087
          console.log(res)
          if(res.data.code == 200) {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 2000
            })
            this.setData({
              showFlag: false
            })
          }
          console.log('25000')
          
        })
      }
    } catch (e) {
      //console.error(e)
    }
  },
  updateAddress() {
    this.setData({
      addressFlag: true
    })
  },
  atuoGetLocation(e) {
    console.log(e.detail.value)
    var _this = this;
    qqMap.geocoder({
      address: e.detail.value,   //用户输入的地址（注：地址中请包含城市名称，否则会影响解析效果），如：'北京市海淀区彩和坊路海淀西大街74号'
      complete: function (res) {
        console.log(res.result.location.lat)
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        // console.log(res.result)
        //根据地址解析在地图上标记解析地址位置
        _this.setData({ // 获取返回结果，放到markers及poi中，并在地图展示
          markers: [{
            id: 0,
            title: res.title,
            latitude: latitude,
            longitude: longitude,
            iconPath: '../../resources/location.png',//图标路径
            width: 20,
            height: 20,
            callout: { //可根据需求是否展示经纬度
              content: e.detail.value.valueAddress,
              color: '#000',
              display: 'ALWAYS'
            }
          }],
          latitude: latitude,
          longitude: longitude
        })
      }
    })
  },
  // 修改地址
  formAddreaaSubmit(e) {
    const ordNo = e.currentTarget.dataset.id
    const address = e.detail.value.valueAddress
    const lng = e.currentTarget.dataset.lng
    const lat = e.currentTarget.dataset.lat
    console.log(e.currentTarget.dataset)
    try {
      const token = wx.getStorageSync('token')
      if (token !== '') {
        request({
          url: '/updateOrderAddress',
          method: 'POST',
          data: {
            token: token,
            ordNo: ordNo,
            address: address,
            lng, lat
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'token': `${token}`
          }
        }).then(res => {
          console.log(res)
          if (res.data.code == 200) {
            Notify({
              message: '修改成功',
              color: '#ad0000',
              background: '#fff639',
            })
            this.setData({
              showFlag: false
            })
          } else {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          }
          console.log('25000')

        })
      }
    } catch (e) {
      //console.error(e)
    }
  },
  cancelUpdateAddress() {
    this.setData({
      addressFlag: false
    })
  },
  // 修改时间
  updateOverTime() {
    this.setData({
      timeFlag: true
    })
  },
  changeDateTime(e) {
    this.setData({ dateTime: e.detail.value });
  },
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({ 
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },
  changeDateTimeEnd(e) {
    this.setData({ dateEndTime: e.detail.value });
  },
  changeDateTimeColumnEnd(e) {
    var arr = this.data.dateEndTime, dateArr = this.data.dateTimeArrayEnd;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({ 
      dateTimeArrayEnd: dateArr,
      dateEndTime: arr
    });
  },
  onClickLeft() {
    wx.showToast({ title: '点击返回', icon: 'none' });
  },
  onClickRight() {
    wx.showToast({ title: '点击按钮', icon: 'none' });
  },
  //开始录音
  updateRecording() {
    wx.startRecord({
      success: function (e) {
        const tempFilePath = res.tempFilePath;
        voice = e.tempFilePath
        wx.uploadFile({
          url: 'xxxxxxxx',//开发者文件上传地址
          filePath: tempFilePath,
          name: 'file',
          success: res => {
            const url = JSON.parse(res.data);//将这个url提交保存
          },
        })
      },
      fail: res => {
        showToast.fail('录音失败');
      },
    })
    setTimeout(() => {
      wx.stopRecord();
    }, 600000);
  },
  // 修改时间timeSubmit
  timeSubmit(e) {
    const ordNo = e.currentTarget.dataset.id
    const delySTime = e.currentTarget.dataset.delystime
    const delyETime = e.currentTarget.dataset.delyetime
    console.log(e)
    try {
      const token = wx.getStorageSync('token')
      if (token !== '') {
        request({
          url: '/updateOrderDeliveryTime',
          method: 'POST',
          data: {
            token,
            ordNo,
            delySTime,
            delyETime
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'token': `${token}`
          }
        }).then(res => {
          console.log(res)
          if (res.data.code == 200) {
            // wx.showToast({
            //   title: '修改成功',
            //   icon: 'success',
            //   duration: 2000
            // })
            Notify({
              message: '修改成功',
              color: '#ad0000',
              background: '#fff639',
            })
            this.setData({
              timeFlag: false
            })
          } else {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          }
          console.log('25000')

        })
      }
    } catch (e) {
      //console.error(e)
    }
  },
  cancelAbnormal() {
    this.setData({
      timeFlag: false
    })
  },
  play: function () {
    //播放声音文件  
    wx.playVoice({
      filePath: voice
    })
  },
  // 播放音频：
  // 小程序播放的音频必须是音频文件，不是文件url
  // 所以首先要将音频下载再进行播放。
  // wx.downloadFile({
  //       url: ‘xxxxxx’, //音频文件url                  
  //       success: res => {                
  //             if (res.statusCode === 200) {                
  //                   wx.playVoice({              
  //                       filePath: res.tempFilePath,             
  //                       duration: this.recordTime,           
  //                         complete: () => {           

  //                         }
  //                   });
  //             }
  //       }
  // });
  stop: function () {
    //结束录音  
    wx.stopRecord();
  },
  bindInput: function(e){
    var that = this;
    var keywords = e.detail.value; 
    // var key = d5e940ac71e33d85ec6ebad1c485e99e;
    var myAmapFun = new amapFile.AMapWX({key: 'd5e940ac71e33d85ec6ebad1c485e99e'});
    myAmapFun.getInputtips({
      keywords: keywords,
      location: '',
      success: function(data){
        console.log('data.tips',data.tips)
        if(data && data.tips){
          that.setData({
            tips: data.tips
          });
        }
      }
    })
  },
  bindSearch: function(e){
    var keywords = e.target.dataset.keywords;
    var url = '../poi/poi?keywords=' + keywords;
    // console.log(url)
    wx.redirectTo({
      url: url
    })
  }
})
